/* 
**    Copyright (C) 2012 Institute for Systems Biology 
**                       Seattle, Washington, USA. 
**
**    This library is free software; you can redistribute it and/or
**    modify it under the terms of the GNU Lesser General Public
**    License as published by the Free Software Foundation; either
**    version 2.1 of the License, or (at your option) any later version.
**
**    This library is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**    Lesser General Public License for more details.
**
**    You should have received a copy of the GNU Lesser General Public
**    License along with this library; if not, write to the Free Software
**    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

var pdr = {};

/***************************************************************
**
** This object does patient data retrieval
*/

pdr.PatientDataRetriever = function(theSource) {
  this.source = theSource;
  this.query = '/query?tq=';
  this.dataDisplay = null;
  this.dataSource = null; 
  this.thePoints = [];
  this.rawPoints = [];
  this.xName = "";
  this.yName = "";
  this.bothHalfs = false;
};

/***************************************************************
**
** What dataset are we getting our data from:
*/

pdr.PatientDataRetriever.prototype.setDataSource = function(dataSource) {
  this.dataSource = dataSource; 
  return;
};

/***************************************************************
**
** What display are we writing to:
*/

pdr.PatientDataRetriever.prototype.setDataDisplay = function(dataDisplay) {
  this.dataDisplay = dataDisplay;
  return;
};

/***************************************************************
**
** Clear the accumulators:
*/

pdr.PatientDataRetriever.prototype.reset = function() {
  this.thePoints = [];
  this.rawPoints = [];
  this.xName = "";
  this.yName = "";
  this.bothHalfs = false;
  return;
};

/***************************************************************
**
** Go launch the acquisition:
*/

pdr.PatientDataRetriever.prototype.getPatientDataFromTags = function(gene1, gene2, type1, type2) {
  this.reset();
  this.getSeparatePatientData(gene1, gene2, true, this.dataSource, type1);
  this.getSeparatePatientData(gene2, gene1, false, this.dataSource, type2);
  return;
};

/***************************************************************
**
** Acquire for each gene:
*/

pdr.PatientDataRetriever.prototype.getSeparatePatientData = function(gene, ogene, isSrc, dataSet, type) {
  var theData = {}; 
  var xmlhttp = new XMLHttpRequest();

  var fullDataSet = dataSet + "_pw_features";
  var patSel = "select%20source,%20%60label%60,%20patient_values%20";
  var patWhere = "where%20%60label%60%20%3D%20'" + gene + "'";
  var whereStr2 = "and%20source%20=%20'" + type + "'";
  var patLim = "%20limit%201";
  var tqx = "&tqx=out:json_array";
      
  var myURL = this.source + fullDataSet + this.query + patSel + patWhere + whereStr2 + patLim + tqx;
  var that = this;
  xmlhttp.open("GET", myURL, true);
  xmlhttp.setRequestHeader('Accept', 'application/json');
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      theData = (xmlhttp.responseText.substring(0, 1) !== "g") ? JSON.parse(xmlhttp.responseText) : null;
      var theSet = (theData === null) ? undefined : theData[0];     
      that.buildHalfPoints(theSet, isSrc, gene);
      if (that.bothHalfs) {
        that.cleanPoints();
        if (isSrc) {
          that.dataDisplay.installData(that.thePoints, gene, ogene);
        } else {
          that.dataDisplay.installData(that.thePoints, ogene, gene);
        }
        that.dataDisplay.render();
      } else {
        that.bothHalfs = true;
      }
    }
  };
  xmlhttp.send();
};

/***************************************************************
**
** Build half of scatterplot data points:
*/

pdr.PatientDataRetriever.prototype.buildHalfPoints = function(theSet, isSrc, gene) {
  if (theSet === undefined) {
    return;
  }
  if (isSrc) {
    this.xName = gene;
  } else {
    this.yName = gene;  
  }
  var tok1 = theSet.patient_values.split(':');
  if ((this.rawPoints.length != 0) && (tok1.length != this.rawPoints.length)) {
    throw {name: 'LengthMismatch', message: 'bad lengths'};
  }
  var firstPass = (this.rawPoints.length === 0);
  for (var i = 0; i < tok1.length; i++) {
    var rawVal = (tok1[i] === 'NA') ? "NA" : parseFloat(tok1[i]);
    if (firstPass) {
      var point = {};
      if (isSrc) {
        point.x = rawVal;
      } else {
        point.y = rawVal;
      }
      this.rawPoints[this.rawPoints.length] = point;
    } else {
      var point = this.rawPoints[i];
      if (isSrc) {
        point.x = rawVal;
      } else {
        point.y = rawVal;
      }
    }   
  };
  return;
};

/***************************************************************
**
** Clean out points that have undefined values:
*/

pdr.PatientDataRetriever.prototype.cleanPoints = function() {
  for (var i = 0; i < this.rawPoints.length; i++) {
    if ((this.rawPoints[i].x === 'NA') || (this.rawPoints[i].y === 'NA')) {
      continue;
    }
    this.thePoints[this.thePoints.length] = this.rawPoints[i];
  };
  return;
};
